

const ajax = options =>{
    const {
        url ,
        type ,
        data = {} ,
        async = true,
        dataType = 'json'
    } = options ;

    let params = '';
    // 遍历data
    for (let key in data) {
        params += `${key}=${data[key]}&`;
    }
    params = params.substring(0, params.length - 1);


    const p = new Promise((resolve, reject) => {
        // 异步的程序
        const xhr = new XMLHttpRequest();

        // 判断请求的方式
        if (type.toLowerCase() === 'get') {
            xhr.open(type, url + '?' + params, async);
            xhr.send();
        }
        else if (type.toLowerCase() === 'post') {
            xhr.open(type, url, true);
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
            xhr.send(params);
        }


        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // resolve('成功啦') ;
                let data = xhr.responseText;
                if(dataType === 'json') {
                    data = JSON.parse(data) ;
                }
                resolve(data);
            } 
        }
    });

    return p
}





